from __future__ import annotations

from src.core.util import log
from typing import TextIO


def read_properties_from_file(file: TextIO) -> dict:
    """
    :param: file the file containing the property data
    :return: property data in dict type
    """
    config = dict()
    lines = file.readlines()
    for line in lines:
        is_comment = line.startswith('#')
        is_empty = len(line.strip()) == 0
        if is_comment or is_empty:
            continue
        parts = line.split('=')
        key = parts[0].strip()
        value = parts[1].strip()
        config[key] = value
    return config


class ConfigReader(object):
    """
    config reader. Contains a inner state "config"
    """
    DEFAULT_CONFIG_FILE_PATH: str = 'resources/config.properties'

    def __init__(self):
        self.__config: dict = dict()

    def read(self, config_file_path: str = DEFAULT_CONFIG_FILE_PATH) -> ConfigReader:
        """
        read configuration
        :param config_file_path: config file path. Required if read from file
        :return: self
        """
        try:
            log.info('Starting reading config...')
            with open(config_file_path, encoding='utf-8') as in_file:
                self.__config = read_properties_from_file(in_file)
            log.info('Config read done!')
            return self
        except FileNotFoundError as e:
            log.error('Could not find file at {}'.format(config_file_path))
            raise e

    def get_config(self):
        return self.__config
